const { getSales, addSales, deleteSales, modifySales, getAllCustomersBelongToTheSales,searchSales,getSaleOne,upDataOne } = require("../dao/modules/salesDao");
const { moveFile, deleteFiles } = require("../util/handleFiles");

// 新增销售员
module.exports.addSales = async function (sales) {
    // 先查询是否已经有这个账号了，如果有就直接返回该账号已被注册。否则就新增
    const result = await searchSales({ username: sales.username });
    if (result.length > 0) {
        return {
            code: 2,
            message: '该销售员账号已被注册',
        }
    } else {
        const data = await addSales(sales);
        if (data) {
            if (data.headSculpture) {
                moveFile({
                    fromPath: "./public/temp",
                    toPath: "./public/images",
                    filename: data.headSculpture
                })
                deleteFiles("./public/temp");
            }
            return {
                code: 1,
                message: '新增销售员成功',
                data
            }
        }
        return {
            message: "新增失败",
            code: 0,
        }
    }
}

// 获取所有销售员数据
module.exports.getSales = async function (params) {
    const data = await getSales(params);
    return {
        code: 1,
        message: '获取销售员成功',
        data
    }
}



// 通过id获取所有销售员数据
module.exports.getSalesById = async function (params) {
    const data = await getSalesById(params);
    return {
        code: 1,
        message: '获取该销售员数据成功',
        data
    }
}



// 删除销售员（软删除）
module.exports.deleteSales = async function (_id) {
    const data = await deleteSales(_id);
    if (data.nModified > 0) {
        return {
            code: 1,
            message: '删除销售员成功',
            data
        }
    }
    return {
        message: "删除失败",
        code: 0
    }
}


// 修改销售员数据
module.exports.modifySales = async function ({ _id, name, age, gender, username, password, phone, state, headSculpture }) {
    const data = await modifySales({ _id, name, age, gender, username, password, phone, state, headSculpture });
    if (data.nModified > 0) {
        if (headSculpture) {
            // moveFile({
            //     fromPath: "./public/temp",
            //     toPath: "./public/images",
            //     filename: headSculpture
            // });
            // deleteFiles("./public/temp");
        }
        return {
            code: 1,
            message: '修改销售员成功',
            data
        }
    }
}

// 查看该销售员负责的客户列表
module.exports.getAllCustomersBelongToTheSales = async function (_id) {
    const data = await getAllCustomersBelongToTheSales(_id);
    return {
        code: 1,
        message: '查看该销售员负责的客户列表成功',
        data
    }
}
//获取一个销售信息
module.exports.getSaleOne = async (val)=>{
        const data = await getSaleOne(val);
        return data
}
//修改一个销售信息
module.exports.upDataOne = async (val)=>{
    const data =await upDataOne(val)
    return data
}


